package licode.unisop.auth.infrastructure.service;

import licode.unisop.auth.client.info.AccountIn;
import licode.unisop.auth.client.info.IdentityIn;
import licode.unisop.auth.client.info.UserIdFindIn;
import licode.unisop.auth.domain.user.gateway.UserGateway;
import licode.unisop.provider.info.UserIdInfo;
import licode.unisop.provider.vo.SiAccount;
import licode.unisop.provider.vo.SiIdentity;
import licode.unisop.provider.vo.SiIdentitySet;
import licode.unisop.provider.vo.SiUser;
import licode.unisop.realm.client.api.SiIdentityQueryService;
import licode.unisop.realm.client.api.SiUserQueryService;
import licode.unisop.realm.client.api.SiUserService;
import licode.unisop.realm.client.info.SiUpdatePasswordIn;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户操作接口
 *
 * @author licode
 */
@Service
public class UserGatewayAuth implements UserGateway {
    @Resource
    private SiUserService siUserService;

    @Resource
    private SiUserQueryService siUserQueryService;

    @Resource
    private SiIdentityQueryService siIdentityQueryService;

    @Override
    public SiUser findUser(AccountIn account) {
        return siUserQueryService.lookupUserByAccount(SiAccount.builder()
                .category(account.getCategory())
                .account(account.getAccount())
                .realmId(account.getRealmId())
                .build());
    }

    @Override
    public SiUser findUser(UserIdFindIn account) {
        return siUserQueryService.lookupUserById(UserIdInfo.builder()
                .realmId(account.getRealmId())
                .userId(account.getUserId())
                .platformId("")
                .build());
    }

    @Override
    public IdentityIn findIdentity(UserIdFindIn idFind) {
        SiIdentitySet info = siIdentityQueryService.findIdentity(UserIdInfo.builder()
                .realmId(idFind.getRealmId())
                .userId(idFind.getUserId())
                .build());

        if (null != info && null != info.getData()) {
            for (SiIdentity identity : info.getData()) {
                if (identity.getAuthType().equals(idFind.getAuthType())) {
                    return IdentityIn.builder()
                            .authCode(identity.getAuthCode())
                            .authType(identity.getAuthType())
                            .subType(identity.getSubType())
                            .authData(identity.getAuthData())
                            .build();
                }
            }
        }

        return null;
    }

    @Override
    public void updatePassword(SiUpdatePasswordIn info) {
        siUserService.updatePassword(info);
    }
}
